package org.ruiyichen.guizhou.agr.ui.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.louisgeek.dropdownviewlib.DateSelectView;
import com.louisgeek.dropdownviewlib.DropDownView;
import com.louisgeek.dropdownviewlib.tools.DateTool;

import org.ruiyichen.guizhou.agr.R;
import org.ruiyichen.guizhou.agr.base.BaseActivity;
import org.ruiyichen.guizhou.agr.base.DataManger;
import org.ruiyichen.guizhou.agr.bean.DicEntity;
import org.ruiyichen.guizhou.agr.bean.Response;
import org.ruiyichen.guizhou.agr.bean.mode.IIrrigatedAreaModel;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.net.OkHttpManager;
import org.ruiyichen.guizhou.agr.ui.mineview.BToast;
import org.ruiyichen.guizhou.agr.ui.mineview.CustomDialog;
import org.ruiyichen.guizhou.agr.ui.mineview.TimePeriodSelector;
import org.ruiyichen.guizhou.agr.utils.ClassUtils;
import org.ruiyichen.guizhou.agr.utils.DateUtils;
import org.ruiyichen.guizhou.agr.utils.StrUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/9/8.
 */

public class IrrigatedDevicePlanActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG_ID = "id";

    DateSelectView
            dsvPlanDateStart,
            dsvPlanDateEnd;
    TextView
            tv_plan_date_size;
    DropDownView
            ddv_plan_Interval_period;

    ImageView ivWeekendIrrigatedSwitch;

    TimePeriodSelector tpsPlanPeriod;

    private IIrrigatedAreaModel curIrrigatedAreaModel;

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.df_activity_irrigated_device_plan);
        curIrrigatedAreaModel = (IIrrigatedAreaModel) getIntent().getSerializableExtra(Constant.ParamKey.IRRIGATED_AREA);
        bOkHttpManager = new OkHttpManager(this, bHandler);
        initData();
    }

    @Override
    protected void initViews() {
        setTitle("灌溉计划").setRightText("保存");

        dsvPlanDateStart = findViewById(R.id.dsv_plan_date_start);
        dsvPlanDateStart.setupDateText(DateTool.parseDate2Str(new Date(System.currentTimeMillis()), DateTool
                .FORMAT_DATE));
        dsvPlanDateEnd = findViewById(R.id.dsv_plan_date_end);
        dsvPlanDateEnd.setupDateText(DateTool.parseDate2Str(new Date(System.currentTimeMillis()), DateTool
                .FORMAT_DATE));
        tv_plan_date_size = findViewById(R.id.tv_plan_date_size);

        ddv_plan_Interval_period = findViewById(R.id.ddv_plan_Interval_period);
        List<DicEntity.DicInfo> periodList = new ArrayList<>();
        periodList.add(new DicEntity.DicInfo("0", "0 (每天灌溉)"));
        periodList.add(new DicEntity.DicInfo("1", "1 (每隔1天灌溉)"));
        periodList.add(new DicEntity.DicInfo("2", "2 (每隔2天灌溉)"));
        periodList.add(new DicEntity.DicInfo("3", "3 (每隔3天灌溉)"));
        periodList.add(new DicEntity.DicInfo("4", "4 (每隔4天灌溉)"));
        periodList.add(new DicEntity.DicInfo("5", "5 (每隔5天灌溉)"));
        periodList.add(new DicEntity.DicInfo("6", "6 (每隔6天灌溉)"));
        periodList.add(new DicEntity.DicInfo("7", "7 (每隔7天灌溉)"));
        ddv_plan_Interval_period.setupDataList(new ClassUtils<DicEntity.DicInfo>().objListToMapList(periodList));

        ivWeekendIrrigatedSwitch = findViewById(R.id.iv_weekend_irrigated_switch);

        tpsPlanPeriod = findViewById(R.id.tps_plan_period);
    }

    @Override
    protected void initEvents() {
        findViewById(R.id.iv_normal_back).setOnClickListener(this);
        findViewById(R.id.tv_normal_other).setOnClickListener(this);
        ivWeekendIrrigatedSwitch.setOnClickListener(this);
        dsvPlanDateStart.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setPlanDateUI();
            }
        });
        dsvPlanDateEnd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setPlanDateUI();
            }
        });
    }

    private void setPlanDateUI() {
        if (verifyWorkDay()) {
            long days = DateUtils.getDays(dsvPlanDateEnd.getSelectData(), dsvPlanDateStart
                    .getSelectData());
            tv_plan_date_size.setText("共" + days + "天");
        }
    }

    /**
     * 验证工作天数是否合法
     *
     * @return
     */
    private boolean verifyWorkDay() {
        if (StrUtil.isEmpty(dsvPlanDateStart.getSelectData())) {
            BToast.getInstance().show("请选择开始日期~");
            return false;
        }
        if (StrUtil.isEmpty(dsvPlanDateEnd.getSelectData())) {
            BToast.getInstance().show("请选择结束日期~");
            return false;
        }
        long days = DateUtils.getDays(dsvPlanDateEnd.getSelectData(), dsvPlanDateStart
                .getSelectData());
        if (days <= 0) {
            BToast.getInstance().show("结束时间必须大于起始时间~");
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_normal_back:
                onBackPressed();
                break;
            case R.id.iv_weekend_irrigated_switch:
                ivWeekendIrrigatedSwitch.setSelected(!ivWeekendIrrigatedSwitch.isSelected());
                break;
            case R.id.tv_normal_other:
                //删除
                CustomDialog dialog = new CustomDialog.Builder(this, CustomDialog.Style.MULTI_TIPS)
                        .setMessage("是否保存该灌溉计划~")
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                saveDevicePlan();
                            }
                        })
                        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setTitle("提示")
                        .create();
                dialog.show();
                break;
        }
    }

    private void initData() {
        /*if (StrUtil.isNotEmpty(getIntent().getStringExtra(TAG_ID))) {
            Map<String, String> body = new HashMap<>();
            body.put("token", DataManger.getInstance().getUserInfo().token);
            body.put("id", getIntent().getStringExtra(TAG_ID));
            bOkHttpManager.httpRequest(Constant.RequestType.SEND_MESSAGE, Constant.POST, body, false, new
                    TypeToken<Response<? extends IIrrigatedAreaFilter, Void>>() {
                    }.getType(), true, false);
        }*/
    }

    private void saveDevicePlan() {
        if (curIrrigatedAreaModel == null) {
            BToast.getInstance().show("灌区信息获取失败~");
            return;
        }
        if (!tpsPlanPeriod.canSubmit()) {
            BToast.getInstance().show("时间段选择异常~");
            return;
        }
        if (!verifyWorkDay()) {
            BToast.getInstance().show("灌溉周期必须大于0~");
            return;
        }
        if (tpsPlanPeriod.getSelectTimeValue() == 0) {
            BToast.getInstance().show("灌溉时段总时间必须大于0~");
            return;
        }
        //landId	int	地块Id
        //irrigName	String	灌区名称
        //irrigType	int	灌溉作业类型
        //irrigState	int	灌溉作业状态
        //irrigInterval	String	间隔周期
        //irrigIsirrigationweekend	String	是否周末灌溉
        //irrigWorkdays	int	工作天数
        //irrigSethours	int	作业设置的总时长
        //irrig_start	String	开始日期
        //irrig_end	String	结束日期
        //irrig_timelist	String	灌溉时段
        Map<String, String> body = new HashMap<>();
        body.put("landId", curIrrigatedAreaModel.landId);
        body.put("irrigName", curIrrigatedAreaModel.irrigName);
        body.put("irrigId", curIrrigatedAreaModel.irrigId);
        body.put("irrigType", curIrrigatedAreaModel.irrigType);
        body.put("irrigState", curIrrigatedAreaModel.irrigState);
        body.put("irrigInterval", ddv_plan_Interval_period.getSelectKey());
        body.put("irrigIsirrigationweekend", ivWeekendIrrigatedSwitch.isSelected() ? "1" : "0");
//        body.put("irrigWorkdays", String.valueOf(DateUtils.getDays(dsvPlanDateEnd.getSelectData(), dsvPlanDateStart
//                .getSelectData())));
        body.put("irrigSethours", String.valueOf(tpsPlanPeriod.getSelectTimeValue()));
        body.put("irrig_start", dsvPlanDateStart.getNowSelectData());
        body.put("irrig_end", dsvPlanDateEnd.getNowSelectData());
        body.put("irrig_timelist", tpsPlanPeriod.getSelectTimePeriodStr());
        bOkHttpManager.httpRequest(Constant.RequestType.UPDATE_IRRIGS_PLAN, Constant.Http.POSTSTRING,
                body, false, new
                TypeToken<Response<Void, Void>>() {
                }.getType(), true, false);
    }


    @Override
    protected void onPostHandle(int requestType, Object response, boolean error, int errorCode, Object obj1, Object obj2) {
        super.onPostHandle(requestType, response, error, errorCode, obj1, obj2);
        if (error) {
            BToast.getInstance().show(getResources().getString(R.string.abnormal));
        } else {
            if (response == null) {
                BToast.getInstance().show(getResources().getString(R.string.datafailure));
            } else {
                if (requestType == Constant.RequestType.UPDATE_IRRIGS_PLAN) {
                    Response<Void, Void> result = (Response<Void, Void>) response;
                    if (result.getCode() == 0) {
                        BToast.getInstance().show(result.getMsg());
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                }
            }
        }
    }
}
